import datetime
import os
from tools.yaml_control import GetYamlData
from config.settings import ConfigHandler


def write_case(case_path, page):
    with open(case_path, 'w', encoding="utf-8") as f:
        f.write(page)

def writePageFiles(classTitle, funcTitle, casePath, yamlPath):
    """
        自动写成 py 文件
        :param yamlPath:yaml的路径
        :param casePath: 生成的py文件地址
        :param classTitle: 类名称, 读取用例中的 caseTitle 作为类名称
        :param funcTitle: 函数名称 caseTitle，首字母小写
        :param caseDetail: 函数描述，读取用例中的描述内容，做为函数描述
        :return:
        """
    Author = GetYamlData(ConfigHandler.config_path).get_yaml_data()['TestName']
    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    page = f'''#!/usr/bin/env python
# -*- coding: utf-8 -*-

from tools.request_control import RequestControl
from config.settings import ConfigHandler
from tools.yaml_data_analysis import CaseData
from tools.regular_control import regular
import os
from tools.teardown_control import TearDownHandler

class {classTitle}(object):
    @staticmethod
    def {funcTitle}(inData):
        """
        :param inData:
        :return:
        """
        res = RequestControl().http_request(eval(inData))
        TearDownHandler().teardown_handle(res)
        return res


if __name__ == '__main__':
    
    TestData = CaseData(os.path.join(ConfigHandler.data_path,'{yamlPath}')).case_process()[0]
    re_data = regular(str(TestData))
    data = {classTitle}().{funcTitle}(re_data)
    print(data)
        '''
    with open(casePath, 'w', encoding="utf-8") as f:
        f.write(page)

def write_testcase_file(markers,allure_epic, allure_feature, class_title,func_title, case_path, yaml_path, file_name, allure_story):
    """

        :param allure_story:
        :param file_name: 文件名称
        :param allure_epic: 项目名称
        :param allure_feature: 模块名称
        :param class_title: 类名称
        :param func_title: 函数名称
        :param case_path: case 路径
        :param yaml_path: yaml 文件路径
        :return:
        """
    conf_data = GetYamlData(ConfigHandler.config_path).get_yaml_data()
    author = conf_data['TestName']
    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    real_time_update_test_cases = conf_data['real_time_update_test_cases']

    page = f'''#!/usr/bin/env python
# -*- coding: utf-8 -*-

import allure
import pytest
from config.settings import ConfigHandler
from tools.yaml_data_analysis import CaseData
from tools.assert_control import Assert
from tools.request_control import RequestControl
from tools.regular_control import regular
from tools.teardown_control import TearDownHandler
import os

TestData = CaseData(os.path.join(ConfigHandler.data_path,'{yaml_path}')).case_process()
re_data = regular(str(TestData))

{markers}
@allure.epic("{allure_epic}")
@allure.feature("{allure_feature}")
class Test{class_title}:

    @allure.story("{allure_story}")
    @pytest.mark.parametrize('in_data', eval(re_data), ids=[i['detail'] for i in TestData])
    def test_{func_title}(self, in_data, case_skip):
        """
        :param :
        :return:
        """

        res = RequestControl().http_request(in_data)
        TearDownHandler().teardown_handle(res)
        Assert(res['assert']).assert_equality(response_data=res['response_data'], 
                                                  sql_data=res['sql_data'])


if __name__ == '__main__':
    pytest.main(['{file_name}', '-s', '-W', 'ignore:Module already imported:pytest.PytestWarning'])
'''
    if real_time_update_test_cases:
        write_case(case_path=case_path, page=page)
    elif real_time_update_test_cases is False:
        if not os.path.exists(case_path):
            write_case(case_path=case_path, page=page)
    else:
        raise ValueError("real_time_update_test_cases 配置不正确，只能配置 True 或者 False")
